package com.bloveoacom.weichi.activity;

import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.text.InputType;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.TextView;

import com.bloveoacom.base.AppContext;
import com.bloveoacom.base.BaseList2Activity;
import com.bloveoacom.base.UserInfoBean;
import com.bloveoacom.exception.ApiException;
import com.bloveoacom.http.HttpMethods;
import com.bloveoacom.http.HttpResult;
import com.bloveoacom.http.RxHelper;
import com.bloveoacom.observer.BaseSubscriber2;
import com.bloveoacom.util.AESCipher;
import com.bloveoacom.util.ActivityUtil;
import com.bloveoacom.util.Constant;
import com.bloveoacom.util.DialogUtil;
import com.bloveoacom.util.GlideUtil;
import com.bloveoacom.util.GsonUtil;
import com.bloveoacom.util.KeyboardUtil;
import com.bloveoacom.util.NumberUtil;
import com.bloveoacom.util.StringUtils;
import com.bloveoacom.util.ToastUtil;
import com.bloveoacom.weichi.R;
import com.bloveoacom.weichi.bean.ActivitysBean;
import com.bloveoacom.weichi.bean.CreateEosWalletBean;
import com.bloveoacom.weichi.bean.NewsPostBean;
import com.bloveoacom.weichi.bean.PostCoinBean;
import com.bloveoacom.weichi.bean.RewardBean;
import com.bloveoacom.weichi.bean.SimpleBean;
import com.bloveoacom.weight.InputDialog;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;

import org.reactivestreams.Publisher;

import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Flowable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

import static com.bloveoacom.util.AESCipher.KEY;
import static com.bloveoacom.util.Constant.ACTIVITY_STATUS_JINXINZHONG;
import static com.bloveoacom.util.Constant.ACTIVITY_STATUS_WEIKAISHI;
import static com.bloveoacom.util.Constant.ACTIVITY_STATUS_YIJIESHU;
import static com.bloveoacom.util.Constant.INTENT_ACTIVITYID;
import static com.bloveoacom.util.DataUtil.setItemView2;
import static com.bloveoacom.util.NumberUtil.isInt;
import static com.bloveoacom.weichi.bean.NewsPostBean.getFromAc;

/**
 * author: yjl
 * e-mail: 1271901673@qq.com
 * time  : 2018/9/21
 * desc  :
 */
public class SearchActivity extends BaseList2Activity<NewsPostBean> {

    private InputDialog inputPasswordDialog;
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.bg_view_one)
    View bg_view_one;
    /**
     *  0从评审列表点击过来的
     *  1.从活动列表点击过来的
     *  2.从微池首页跳转过来的
     */
    private int whereFrom = 0;
    @Override
    protected int getItemLayout() {
        return whereFrom!=1?R.layout.rv_item_post3:R.layout.rv_item_activity;
    }
    private void showInputPasswordDialog() {
        if (inputPasswordDialog == null) {
            inputPasswordDialog = new InputDialog(this, "输入密码", "Password", true, false, R.style.MyDialogStyle);
            inputPasswordDialog.setItemClickListener(new InputDialog.ItemClickListener() {
                @Override
                public void left() {

                }

                @Override
                public void right(String content) {
                    DialogUtil.dissDialog(inputPasswordDialog);
                    BaseSubscriber2<Object> objectBaseSubscriber2 =  HttpMethods.getInstance().getHttpService().findTimeStamp(UserInfoBean.getInstance().getToken()).subscribeOn(Schedulers.io()).flatMap(new Function<HttpResult<Object>, Publisher<HttpResult<Object>>>() {
                        @Override
                        public Publisher<HttpResult<Object>> apply(HttpResult<Object> objectHttpResult) throws Exception {
                            if (objectHttpResult.isOk()) {
                                Object o = objectHttpResult.data;
                                SimpleBean simpleBean = GsonUtil.GsonToBean(GsonUtil.GsonString(o), SimpleBean.class);
                                String s = AESCipher.decryptAES(simpleBean.timeStamp);
                                CreateEosWalletBean transInfoBean = new CreateEosWalletBean(content, s);
                                String sign = AESCipher.encryptAES(GsonUtil.GsonString(transInfoBean), KEY);
                                return HttpMethods.getInstance().getHttpService().getReviewCoinNewsDetail(UserInfoBean.getInstance().getToken(),bean.coinId,sign);
                            } else {
                                return Flowable.error(new ApiException(objectHttpResult.code, objectHttpResult.msg));
                            }
                        }
                    }).compose(RxHelper.getData()).subscribeWith(new BaseSubscriber2<Object>(SearchActivity.this){
                        @Override
                        public void onNext(Object o) {
                            super.onNext(o);
                            bean.isReview = 1;
                            ActivityUtil.startActivity(mContext,PostDetail2Activity.class,bean.coinId,String.valueOf(bean.isVote));
                        }
                    });
                    addDispose(objectBaseSubscriber2);

                }
            });
        }
        inputPasswordDialog.show();
    }

    @Override
    protected View getViewSetTB() {
        return bg_view_one;
    }

    @Override
    protected void convertView(BaseViewHolder helper, NewsPostBean item) {
        switch (whereFrom) {
            case 0:
            case 2:
                setItemView2(mContext,helper,item,3);
                break;
            case 1:
                GlideUtil.loadRoundmage(helper.getView(R.id.iv_image), StringUtils.getFullUrl(item.posters, 0));
                if (item.getIsCanTicket()) {
                    helper.setText(R.id.tv_buy, "去购买");
                    helper.setBackgroundRes(R.id.tv_buy, R.drawable.shape_buy);
                } else {
                    //未购票
                    if(item.isCanTicket==1){
                        helper.setText(R.id.tv_buy, "已购票");
                    }else{
                        helper.setText(R.id.tv_buy, "去购买");
                    }
                    helper.setBackgroundRes(R.id.tv_buy, R.drawable.shape_buy_gray);
                }
                if(item.activityStatus==ACTIVITY_STATUS_WEIKAISHI){
                    helper.setText(R.id.tv_state, "未开始");
                    helper.setTextColor(R.id.tv_state, ContextCompat.getColor(this,R.color.black));
                } if(item.activityStatus==ACTIVITY_STATUS_JINXINZHONG){
                helper.setText(R.id.tv_state, "活动中");
                helper.setTextColor(R.id.tv_state, ContextCompat.getColor(this,R.color.activity_state));
            } if(item.activityStatus==ACTIVITY_STATUS_YIJIESHU){
                helper.setText(R.id.tv_state, "已结束");
                helper.setTextColor(R.id.tv_state, ContextCompat.getColor(this,R.color.black));
            }
                break;
        }


    }

    @Override
    protected void getData() {

    }


    @Override
    public int getLayoutResId() {
        return R.layout.activity_search;
    }

    @Override
    public void getBundleExtras(Bundle extras) {
        if(extras.containsKey(Constant.DATA0)){
            whereFrom = NumberUtil.getIntByStr(extras.getString(Constant.DATA0));
        }

    }

    @Override
    public boolean isLoadMore() {
        return false;
    }

    @Override
    protected boolean isOpenRefresh() {
        return false;
    }

    @Override
    public void initView() {
        super.initView();
        if(whereFrom==0){
            etSearch.setHint("文章ID");
            etSearch.setInputType(InputType.TYPE_CLASS_NUMBER);
        }else if(whereFrom==1){
            etSearch.setHint("活动");
        }else if(whereFrom==2){
            etSearch.setHint("文章标题");
        }
    }

    private String key;
    @Override
    public void initListener() {
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    //完成自己的事件
                    key = etSearch.getText().toString().trim();
                    if (StringUtils.isEmpty(key)) {
                        ToastUtil.makeShortText(mContext, "请输入内容");
                        return false;
                    }
                    if(whereFrom==0){
                        BaseSubscriber2<NewsPostBean> baseSubscriber2 = HttpMethods.getInstance().getHttpService().queryReviewCoinNew(UserInfoBean.getInstance().getToken(), key).compose(RxHelper.getData()).subscribeWith(new BaseSubscriber2<NewsPostBean>(SearchActivity.this) {
                            @Override
                            public void onNext(NewsPostBean o) {
                                datas.clear();
                                datas.add(o);
                                adapter.notifyDataSetChanged();
                            }
                        });
                        addDispose(baseSubscriber2);
                    }else if(whereFrom==1){
                        BaseSubscriber2<List<ActivitysBean>> baseSubscriber2 = HttpMethods.getInstance().getHttpService().getActivityList(  page, getPageSize(),UserInfoBean.getInstance().getToken(),key).compose(RxHelper.getData()).subscribeWith(new BaseSubscriber2<List<ActivitysBean>>() {
                            @Override
                            public void onNext(List<ActivitysBean> o) {
                                datas.clear();
                                datas.addAll(getFromAc(o));
                                adapter.notifyDataSetChanged();


                            }
                        });
                        addDispose(baseSubscriber2);
                    }else if(whereFrom==2){
                        BaseSubscriber2<PostCoinBean> baseSubscriber2 = HttpMethods.getInstance().getHttpService().getCoinNewsList(page, getPageSize(),"0",key).compose(RxHelper.io_main()).subscribeWith(new BaseSubscriber2<PostCoinBean>() {
                            @Override
                            public void onNext(PostCoinBean o) {
                                datas.clear();
                                datas.addAll(o.getData());
                                adapter.notifyDataSetChanged();

                            }
                        });
                        addDispose(baseSubscriber2);
                    }
                }
                return false;
            }
        });

        adapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                bean = datas.get(position);
                if(whereFrom==0){
                    if(!"1".equals(String.valueOf(bean.isReview))){
                        showInputPasswordDialog();
                    }else{
                        ActivityUtil.startActivity(mContext,PostDetail2Activity.class,bean.coinId,String.valueOf(bean.isVote));
                    }
                }else if(whereFrom==1){
                    Bundle bundle=new Bundle();
                    bundle.putString(INTENT_ACTIVITYID,datas.get(position).activityId);
                    ActivityUtil.startActivity(mContext,ActivityDetailActivity.class,bundle);
                }

            }
        });

    }

    private NewsPostBean bean;

    @OnClick(R.id.iv_back)
    public void onViewClicked() {
        KeyboardUtil.closeKeyboard(this);
        finish();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
